/*
 *	Copyright 2011 andro-inject developers 
 *	Licensed under the Apache License, Version 2.0 (the "License"); 
 *	you may not use this file except in compliance with the License. 
 *	You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 * 
 *	Unless required by applicable law or agreed to in writing, software 
 *	distributed under the License is distributed on an "AS IS" BASIS,
 *	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *	See the License for the specific language governing permissions and
 *	limitations under the License. 
 * 
*/

package com.androinject.core.factory.xml;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.androinject.core.definitions.ComponentDefinitions;
import com.androinject.core.factory.AbstractComponentFactory;
import com.androinject.core.factory.exceptions.UnableToReadComponentDefinitionsException;
import com.androinject.core.factory.input.InputSource;

public abstract class XmlComponentFactory extends AbstractComponentFactory {

	
	@Override
	protected ComponentDefinitions getComponentDefinitions() throws UnableToReadComponentDefinitionsException {
		try {
			return this.parseXmlContent(this.getInputSource().getInputStream());
		} catch (Exception e) {
			throw new UnableToReadComponentDefinitionsException("An error occurred while reading component configuration from xml file.", e);
		}
	}
	
	
	protected ComponentDefinitions parseXmlContent(InputStream inputStream) throws SAXException, IOException, ParserConfigurationException {
		SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
		SaxHandler saxHandler = new SaxHandler();
		
		XMLReader xmlReader = saxParser.getXMLReader();
		xmlReader.setContentHandler(saxHandler);
		xmlReader.parse(new org.xml.sax.InputSource(inputStream));
		
		return saxHandler.getComponentDefinitions();
	}

	
	protected abstract InputSource getInputSource();

}
